using System.Collections;
using UnityEngine;

namespace VoxelEngine.Utils
{
	public class AutoDestroy : MonoBehaviour
	{
		[SerializeField]
		private float _time;

		[SerializeField]
		private bool _returnToPool;

		private ParticleSystem _particleSystem;

		private ParticleSystem[] _subParticleSystem;

		private void Awake()
		{
			_particleSystem = base.gameObject.GetComponent<ParticleSystem>();
			_subParticleSystem = base.gameObject.GetComponentsInChildren<ParticleSystem>();
		}

		private void OnEnable()
		{
			if (_subParticleSystem != null)
			{
				for (int i = 0; i < _subParticleSystem.Length; i++)
				{
					_subParticleSystem[i].Play();
				}
			}
			StartCoroutine(WaitAndDestroy());
		}

		private IEnumerator WaitAndDestroy()
		{
			yield return new WaitForSeconds(_time);
			if (!_returnToPool)
			{
				UnityEngine.Object.DestroyImmediate(base.gameObject);
				yield break;
			}
			if (_particleSystem != null)
			{
				_particleSystem.Stop();
			}
			DynamicObjectPool.Instance.ReturnObject(base.gameObject);
		}
	}
}
